<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"wan-lei8.gitee.io","root":"/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="MapStruct是专门用来处理 domin 实体类与 model 类的属性映射的，我们只需定义 mapper 接口，MapStruct在编译的时候就会自动的帮我们实现这个映射接口，避免了麻烦复杂的映射实现。 为啥不用 BeanUtils 的 copyProperties 方法呢？不也照样可以实现属性的映射么？ BeanUtils 就是一个大老粗，只能同属性映射，或者在属性相同的情况下，允许被映射">
<meta property="og:type" content="article">
<meta property="og:title" content="MapStruct实现属性映射">
<meta property="og:url" content="https://wan-lei8.gitee.io/2022/01/12/MapStruct%E5%AE%9E%E7%8E%B0%E5%B1%9E%E6%80%A7%E6%98%A0%E5%B0%84/index.html">
<meta property="og:site_name" content="程序员西桐">
<meta property="og:description" content="MapStruct是专门用来处理 domin 实体类与 model 类的属性映射的，我们只需定义 mapper 接口，MapStruct在编译的时候就会自动的帮我们实现这个映射接口，避免了麻烦复杂的映射实现。 为啥不用 BeanUtils 的 copyProperties 方法呢？不也照样可以实现属性的映射么？ BeanUtils 就是一个大老粗，只能同属性映射，或者在属性相同的情况下，允许被映射">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img2020.cnblogs.com/blog/1196304/202004/1196304-20200419220449255-1694950350.png">
<meta property="og:image" content="https://img2020.cnblogs.com/blog/1196304/202004/1196304-20200419222139713-1264721190.png">
<meta property="og:image" content="https://img2020.cnblogs.com/blog/1196304/202004/1196304-20200419224049611-2091880707.png">
<meta property="og:image" content="https://img2020.cnblogs.com/blog/1196304/202004/1196304-20200419230431692-1356570810.png">
<meta property="article:published_time" content="2022-01-12T03:34:08.000Z">
<meta property="article:modified_time" content="2022-01-12T03:53:24.383Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img2020.cnblogs.com/blog/1196304/202004/1196304-20200419220449255-1694950350.png">

<link rel="canonical" href="https://wan-lei8.gitee.io/2022/01/12/MapStruct%E5%AE%9E%E7%8E%B0%E5%B1%9E%E6%80%A7%E6%98%A0%E5%B0%84/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>MapStruct实现属性映射 | 程序员西桐</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">程序员西桐</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">但行好事，莫问前程</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wan-lei8.gitee.io/2022/01/12/MapStruct%E5%AE%9E%E7%8E%B0%E5%B1%9E%E6%80%A7%E6%98%A0%E5%B0%84/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.png">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="程序员西桐">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          MapStruct实现属性映射
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2022-01-12 11:34:08 / 修改时间：11:53:24" itemprop="dateCreated datePublished" datetime="2022-01-12T11:34:08+08:00">2022-01-12</time>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>MapStruct是专门用来处理 domin 实体类与 model 类的属性映射的，我们只需定义 mapper 接口，MapStruct在编译的时候就会自动的帮我们实现这个映射接口，避免了麻烦复杂的映射实现。</p>
<p>为啥不用 <code>BeanUtils</code> 的 <code>copyProperties</code> 方法呢？不也照样可以实现属性的映射么？</p>
<p><code>BeanUtils</code> 就是一个大老粗，只能同属性映射，或者在属性相同的情况下，允许被映射的对象属性少；但当遇到被映射的属性数据类型被修改或者被映射的字段名被修改，则会导致映射失败。</p>
<p>而 <code>mapstruct</code> 就是一个巧媳妇儿了，她心思细腻，把我们可能会遇到的情况都给考虑到了</p>
<h4 id="准备工作"><a href="#准备工作" class="headerlink" title="准备工作"></a>准备工作</h4><ol>
<li>@Mapper注解</li>
</ol>
<p>从 mybatis3.4.0 开始加入的 @Mapper 注解，目的就是为了不再写mapper映射文件。</p>
<p>我们只需要在 dao 层定义的接口上使用注解就可以实现sql语句的编写，例如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Select(&quot;select * from user where name = #&#123;name&#125;&quot;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> User <span class="title">find</span><span class="params">(String name)</span></span>;</span><br></pre></td></tr></table></figure>

<p>如上就是一个简单的使用，虽然简单，但也确实体现出了这个注解的优越性，至少少写了一个xml文件。</p>
<p>MapStruct 的 <code>@Mapper</code> 注解的 <code>componentModel</code> 属性，<code>componentModel</code> 属性用于指定自动生成的接口实现类的组件类型，这个属性支持四个值：</p>
<ul>
<li>default: 这是默认的情况，mapstruct 不使用任何组件类型, 可以通过Mappers.getMapper(Class)方式获取自动生成的实例对象。</li>
<li>cdi: the generated mapper is an application-scoped CDI bean and can be retrieved via @Inject</li>
<li>spring: 生成的实现类上面会自动添加一个@Component注解，可以通过Spring的 @Autowired方式进行注入</li>
<li>jsr330: 生成的实现类上会添加@javax.inject.Named 和@Singleton注解，可以通过 @Inject注解获取</li>
</ul>
<ol start="2">
<li><p>依赖</p>
<p>首先需要把依赖包导入，主要由两个包组成：</p>
<ul>
<li><code>org.mapstruct:mapstruct</code>：包含了一些必要的注解，例如@Mapping。r若我们使用的JDK版本高于1.8，当我们在pom里面导入依赖时候，建议使用坐标是：<code>org.mapstruct:mapstruct-jdk8</code>，这可以帮助我们利用一些Java8的新特性。</li>
<li><code>org.mapstruct:mapstruct-processor</code>：注解处理器，根据注解自动生成mapper的实现。</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&lt;dependency&gt;</span><br><span class="line">       &lt;groupId&gt;org.mapstruct&lt;/groupId&gt;</span><br><span class="line">       &lt;!-- jdk8以下就使用mapstruct --&gt;</span><br><span class="line">       &lt;artifactId&gt;mapstruct-jdk8&lt;/artifactId&gt;</span><br><span class="line">       &lt;version&gt;<span class="number">1.2</span><span class="number">.0</span>.Final&lt;/version&gt;</span><br><span class="line">   &lt;/dependency&gt;</span><br><span class="line">   &lt;dependency&gt;</span><br><span class="line">       &lt;groupId&gt;org.mapstruct&lt;/groupId&gt;</span><br><span class="line">       &lt;artifactId&gt;mapstruct-processor&lt;/artifactId&gt;</span><br><span class="line">       &lt;version&gt;<span class="number">1.2</span><span class="number">.0</span>.Final&lt;/version&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></figure></li>
</ol>
<h4 id="使用"><a href="#使用" class="headerlink" title="使用"></a>使用</h4><ol>
<li><p>定义实体类以及被映射类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 实体类</span></span><br><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@NoArgsConstructor</span></span><br><span class="line"><span class="meta">@AllArgsConstructor</span></span><br><span class="line"><span class="meta">@Builder</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> Integer id;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    <span class="keyword">private</span> String createTime;</span><br><span class="line">    <span class="keyword">private</span> LocalDateTime updateTime;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 被映射类VO1:和实体类一模一样</span></span><br><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@NoArgsConstructor</span></span><br><span class="line"><span class="meta">@AllArgsConstructor</span></span><br><span class="line"><span class="meta">@Builder</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserVO1</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> Integer id;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    <span class="keyword">private</span> String createTime;</span><br><span class="line">    <span class="keyword">private</span> LocalDateTime updateTime;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 被映射类VO1:比实体类少一个字段</span></span><br><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@NoArgsConstructor</span></span><br><span class="line"><span class="meta">@AllArgsConstructor</span></span><br><span class="line"><span class="meta">@Builder</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserVO2</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> Integer id;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    <span class="keyword">private</span> String createTime;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li><p>定义接口</p>
<p>当实体类和被映射对象属性相同或者被映射对象属性值少几个时：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Mapper(componentModel = &quot;spring&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">UserCovertBasic</span> </span>&#123;</span><br><span class="line">    UserCovertBasic INSTANCE = Mappers.getMapper(UserCovertBasic.class);</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 字段数量类型数量相同，利用工具BeanUtils也可以实现类似效果</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> source</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function">UserVO1 <span class="title">toConvertVO1</span><span class="params">(User source)</span></span>;</span><br><span class="line">    <span class="function">User <span class="title">fromConvertEntity1</span><span class="params">(UserVO1 userVO1)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 字段数量类型相同,数量少：仅能让多的转换成少的，故没有fromConvertEntity2</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> source</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function">UserVO2 <span class="title">toConvertVO2</span><span class="params">(User source)</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ol>
<h4 id="测试"><a href="#测试" class="headerlink" title="测试"></a>测试</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TestController</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping(&quot;convert&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">convertEntity</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        User user = User.builder()</span><br><span class="line">                .id(<span class="number">1</span>)</span><br><span class="line">                .name(<span class="string">&quot;张三&quot;</span>)</span><br><span class="line">                .createTime(<span class="string">&quot;2020-04-01 11:05:07&quot;</span>)</span><br><span class="line">                .updateTime(LocalDateTime.now())</span><br><span class="line">                .build();</span><br><span class="line">        List&lt;Object&gt; objectList = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line"></span><br><span class="line">        objectList.add(user);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 使用mapstruct</span></span><br><span class="line">        UserVO1 userVO1 = UserCovertBasic.INSTANCE.toConvertVO1(user);</span><br><span class="line">        objectList.add(<span class="string">&quot;userVO1:&quot;</span> + UserCovertBasic.INSTANCE.toConvertVO1(user));</span><br><span class="line">        objectList.add(<span class="string">&quot;userVO1转换回实体类user:&quot;</span> + UserCovertBasic.INSTANCE.fromConvertEntity1(userVO1));</span><br><span class="line">        <span class="comment">// 输出转换结果</span></span><br><span class="line">        objectList.add(<span class="string">&quot;userVO2:&quot;</span> + <span class="string">&quot; | &quot;</span> + UserCovertBasic.INSTANCE.toConvertVO2(user));</span><br><span class="line">        <span class="comment">// 使用BeanUtils</span></span><br><span class="line">        UserVO2 userVO22 = <span class="keyword">new</span> UserVO2();</span><br><span class="line">        BeanUtils.copyProperties(user, userVO22);</span><br><span class="line">        objectList.add(<span class="string">&quot;userVO22:&quot;</span> + <span class="string">&quot; | &quot;</span> + userVO22);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> objectList;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="查看编译结果"><a href="#查看编译结果" class="headerlink" title="查看编译结果"></a>查看编译结果</h4><p>通过IDE的反编译功能查看编译后自动生成 <code>UserCovertBasic</code> 的实现类 <code>UserCovertBasicImpl</code> ，内容如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserCovertBasicImpl</span> <span class="keyword">implements</span> <span class="title">UserCovertBasic</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">UserCovertBasicImpl</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> UserVO1 <span class="title">toConvertVO1</span><span class="params">(User source)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (source == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            UserVO1 userVO1 = <span class="keyword">new</span> UserVO1();</span><br><span class="line">            userVO1.setId(source.getId());</span><br><span class="line">            userVO1.setName(source.getName());</span><br><span class="line">            userVO1.setCreateTime(source.getCreateTime());</span><br><span class="line">            userVO1.setUpdateTime(source.getUpdateTime());</span><br><span class="line">            <span class="keyword">return</span> userVO1;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> User <span class="title">fromConvertEntity1</span><span class="params">(UserVO1 userVO1)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (userVO1 == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            User user = <span class="keyword">new</span> User();</span><br><span class="line">            user.setId(userVO1.getId());</span><br><span class="line">            user.setName(userVO1.getName());</span><br><span class="line">            user.setCreateTime(userVO1.getCreateTime());</span><br><span class="line">            user.setUpdateTime(userVO1.getUpdateTime());</span><br><span class="line">            <span class="keyword">return</span> user;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> UserVO2 <span class="title">toConvertVO2</span><span class="params">(User source)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (source == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            UserVO2 userVO2 = <span class="keyword">new</span> UserVO2();</span><br><span class="line">            userVO2.setId(source.getId());</span><br><span class="line">            userVO2.setName(source.getName());</span><br><span class="line">            userVO2.setCreateTime(source.getCreateTime());</span><br><span class="line">            <span class="keyword">return</span> userVO2;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="查看结果"><a href="#查看结果" class="headerlink" title="查看结果"></a>查看结果</h4><p><img src="https://img2020.cnblogs.com/blog/1196304/202004/1196304-20200419220449255-1694950350.png" alt="img"></p>
<p>如果是要转换一个集合的话，只需要把这里的实体类换成集合就行了，例如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">List&lt;UserVO1&gt; <span class="title">toConvertVOList</span><span class="params">(List&lt;User&gt; source)</span></span>;</span><br></pre></td></tr></table></figure>

<h4 id="复制情况"><a href="#复制情况" class="headerlink" title="复制情况"></a>复制情况</h4><ol>
<li><p>类型不一致</p>
<p>实体类我们还是沿用 <code>User</code>；被映射对象 <code>UserVO3</code> 改为：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@NoArgsConstructor</span></span><br><span class="line"><span class="meta">@AllArgsConstructor</span></span><br><span class="line"><span class="meta">@Builder</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserVO3</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> String id;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    <span class="comment">// 实体类该属性是String</span></span><br><span class="line">    <span class="keyword">private</span> LocalDateTime createTime;</span><br><span class="line">    <span class="comment">// 实体类该属性是LocalDateTime</span></span><br><span class="line">    <span class="keyword">private</span> String updateTime;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>那么我们定义的接口就要稍稍修改一下了：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Mappings(&#123;</span></span><br><span class="line"><span class="meta">            @Mapping(target = &quot;createTime&quot;, expression = &quot;java(com.java.mmzsblog.util.DateTransform.strToDate(source.getCreateTime()))&quot;),</span></span><br><span class="line"><span class="meta">    &#125;)</span></span><br><span class="line">    <span class="function">UserVO3 <span class="title">toConvertVO3</span><span class="params">(User source)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="function">User <span class="title">fromConvertEntity3</span><span class="params">(UserVO3 userVO3)</span></span>;</span><br></pre></td></tr></table></figure>

<p>上面 <code>expression</code> 指定的表达式内容如下:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DateTransform</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> LocalDateTime <span class="title">strToDate</span><span class="params">(String str)</span></span>&#123;</span><br><span class="line">        DateTimeFormatter df = DateTimeFormatter.ofPattern(<span class="string">&quot;yyy-MM-dd HH:mm:ss&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> LocalDateTime.parse(<span class="string">&quot;2018-01-12 17:07:05&quot;</span>,df);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>通过IDE的反编译功能查看编译后的实现类，结果是这样子的：</p>
<p><img src="https://img2020.cnblogs.com/blog/1196304/202004/1196304-20200419222139713-1264721190.png" alt="img"></p>
</li>
</ol>
<p>从图中我们可以看到，编译时使用了expression中定义的表达式对目标字段 <code>createTime</code> 进行了转换；然后你还会发现 <code>updateTime</code> 字段也被自动从 LocalDateTime 类型转换成了 String 类型。</p>
<h4 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h4><p>当字段类型不一致时，以下的类型之间是 <code>mapstruct</code> 自动进行类型转换的:</p>
<ul>
<li>基本类型及其他们对应的包装类型。<br>此时 <code>mapstruct</code> 会自动进行拆装箱。不需要人为的处理</li>
<li>基本类型的包装类型和string类型之间</li>
<li>除此之外的类型转换我们可以通过定义表达式来进行指定转换</li>
</ul>
<h4 id="字段名不一致"><a href="#字段名不一致" class="headerlink" title="字段名不一致"></a>字段名不一致</h4><p>实体类我们还是沿用 <code>User</code>；被映射对象 <code>UserVO4</code> 改为：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@NoArgsConstructor</span></span><br><span class="line"><span class="meta">@AllArgsConstructor</span></span><br><span class="line"><span class="meta">@Builder</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserVO4</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 实体类该属性名是id</span></span><br><span class="line">    <span class="keyword">private</span> String userId;</span><br><span class="line">    <span class="comment">// 实体类该属性名是name</span></span><br><span class="line">    <span class="keyword">private</span> String userName;</span><br><span class="line">    <span class="keyword">private</span> String createTime;</span><br><span class="line">    <span class="keyword">private</span> String updateTime;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>那么我们定义的接口就要稍稍修改一下了：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Mappings(&#123;</span></span><br><span class="line"><span class="meta">            @Mapping(source = &quot;id&quot;, target = &quot;userId&quot;),</span></span><br><span class="line"><span class="meta">            @Mapping(source = &quot;name&quot;, target = &quot;userName&quot;)</span></span><br><span class="line"><span class="meta">    &#125;)</span></span><br><span class="line">    <span class="function">UserVO4 <span class="title">toConvertVO</span><span class="params">(User source)</span></span>;</span><br><span class="line">    </span><br><span class="line">    <span class="function">User <span class="title">fromConvertEntity</span><span class="params">(UserVO4 userVO4)</span></span>;</span><br></pre></td></tr></table></figure>

<p>通过IDE的反编译功能查看编译后的实现类，编译后的结果是这样子的：</p>
<p><img src="https://img2020.cnblogs.com/blog/1196304/202004/1196304-20200419224049611-2091880707.png" alt="img"></p>
<p>很明显， <code>mapstruct</code> 通过读取我们配置的字段名对应关系，帮我们把它们赋值在了相对应的位置上，可以说是相当优秀了，但这也仅仅是优秀，而更秀的还请继续往下看：</p>
<h4 id="小结-1"><a href="#小结-1" class="headerlink" title="小结"></a>小结</h4><p>当字段名不一致时，通过使用 <code>@Mappings</code> 注解指定对应关系，编译后即可实现对应字段的赋值。</p>
<h4 id="属性是枚举类型"><a href="#属性是枚举类型" class="headerlink" title="属性是枚举类型"></a>属性是枚举类型</h4><p>实体类我们还是改用 <code>UserEnum</code>:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@NoArgsConstructor</span></span><br><span class="line"><span class="meta">@AllArgsConstructor</span></span><br><span class="line"><span class="meta">@Builder</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserEnum</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> Integer id;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    <span class="keyword">private</span> UserTypeEnum userTypeEnum;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>被映射对象 <code>UserVO5</code> 改为:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@NoArgsConstructor</span></span><br><span class="line"><span class="meta">@AllArgsConstructor</span></span><br><span class="line"><span class="meta">@Builder</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserVO5</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> Integer id;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    <span class="keyword">private</span> String type;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>枚举对象是：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Getter</span></span><br><span class="line"><span class="meta">@AllArgsConstructor</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">enum</span> <span class="title">UserTypeEnum</span> </span>&#123;</span><br><span class="line">    Java(<span class="string">&quot;000&quot;</span>, <span class="string">&quot;Java开发工程师&quot;</span>),</span><br><span class="line">    DB(<span class="string">&quot;001&quot;</span>, <span class="string">&quot;数据库管理员&quot;</span>),</span><br><span class="line">    LINUX(<span class="string">&quot;002&quot;</span>, <span class="string">&quot;Linux运维员&quot;</span>);</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">private</span> String value;</span><br><span class="line">    <span class="keyword">private</span> String title;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>那么我们定义的接口还是照常定义，不会受到它是枚举就有所变化：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Mapping(source = &quot;userTypeEnum&quot;, target = &quot;type&quot;)</span></span><br><span class="line">    <span class="function">UserVO5 <span class="title">toConvertVO5</span><span class="params">(UserEnum source)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="function">UserEnum <span class="title">fromConvertEntity5</span><span class="params">(UserVO5 userVO5)</span></span>;</span><br></pre></td></tr></table></figure>

<p>通过IDE的反编译功能查看编译后的实现类，编译后的结果是这样子的：</p>
<p><img src="https://img2020.cnblogs.com/blog/1196304/202004/1196304-20200419230431692-1356570810.png" alt="img"></p>
<p>很明显， <code>mapstruct</code> 通过枚举类型的内容，帮我们把枚举类型转换成字符串，并给type赋值，可谓是小心使得万年船啊。</p>

    </div>
<div>
  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

  
</div>

    
    
    
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://wan-lei8.gitee.io/2022/01/12/MapStruct%E5%AE%9E%E7%8E%B0%E5%B1%9E%E6%80%A7%E6%98%A0%E5%B0%84/" title="MapStruct实现属性映射">https://wan-lei8.gitee.io/2022/01/12/MapStruct实现属性映射/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2022/01/10/bug-record/" rel="prev" title="bug_record">
      <i class="fa fa-chevron-left"></i> bug_record
    </a></div>
      <div class="post-nav-item">
    <a href="/2022/01/12/LocalDateTime%E4%BD%BF%E7%94%A8/" rel="next" title="LocalDateTime使用">
      LocalDateTime使用 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%87%86%E5%A4%87%E5%B7%A5%E4%BD%9C"><span class="nav-number">1.</span> <span class="nav-text">准备工作</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8"><span class="nav-number">2.</span> <span class="nav-text">使用</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%B5%8B%E8%AF%95"><span class="nav-number">3.</span> <span class="nav-text">测试</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%9F%A5%E7%9C%8B%E7%BC%96%E8%AF%91%E7%BB%93%E6%9E%9C"><span class="nav-number">4.</span> <span class="nav-text">查看编译结果</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%9F%A5%E7%9C%8B%E7%BB%93%E6%9E%9C"><span class="nav-number">5.</span> <span class="nav-text">查看结果</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%A4%8D%E5%88%B6%E6%83%85%E5%86%B5"><span class="nav-number">6.</span> <span class="nav-text">复制情况</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%B0%8F%E7%BB%93"><span class="nav-number">7.</span> <span class="nav-text">小结</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%AD%97%E6%AE%B5%E5%90%8D%E4%B8%8D%E4%B8%80%E8%87%B4"><span class="nav-number">8.</span> <span class="nav-text">字段名不一致</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%B0%8F%E7%BB%93-1"><span class="nav-number">9.</span> <span class="nav-text">小结</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%B1%9E%E6%80%A7%E6%98%AF%E6%9E%9A%E4%B8%BE%E7%B1%BB%E5%9E%8B"><span class="nav-number">10.</span> <span class="nav-text">属性是枚举类型</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt=""
      src="/images/avatar.png">
  <p class="site-author-name" itemprop="name"></p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives">
          <span class="site-state-item-count">41</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/yourname" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;yourname" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="/malegod958@163.com" title="E-Mail → malegod958@163.com"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2018 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">万磊</span>
</div>
  <div class="powered-by">

  </div>

        








      </div>
    </footer>
  </div>

  
  
  <script color='' opacity='0.5' zIndex='-1' count='99' src="/lib/canvas-nest/canvas-nest.min.js"></script>
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

  
	<script type="text/javascript" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
	

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/clicklove.js"></script>
